namespace Sustainalytics.ESGComputing.Service.Extensions
{
    using System;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http.Filters;

    using Sustainalytics.ESGComputing.Service.Helpers;
    using Sustainalytics.ESGRatings.DataContract;

    public static class HttpActionExecutionContextExtensions
    {
        public static HttpActionExecutedContext SetErrorResponseFor<T>(this HttpActionExecutedContext context, HttpStatusCode statusCode, string message = null)
        {
            if (context.Response == null && context.Exception is T)
            {
                context.Response = context.Request.CreateErrorResponse(statusCode, message ?? context.Exception.Message);
            }

            return context;
        }

        public static HttpActionExecutedContext SetErrorResponseFor<T>(this HttpActionExecutedContext context, HttpStatusCode statusCode, ErrorModel errorModel = null)
        {
            if (context.Response == null && context.Exception is T)
            {
                context.Response = context.Request.CreateResponse(
                    statusCode,
                    errorModel ?? new ErrorModel { ErrorStatusCode = (int)ErrorCodes.UnknownError, ErrorMessage = context.Exception.Message });
            }

            return context;
        }


        public static HttpActionExecutedContext SetErrorResponseFor(this HttpActionExecutedContext context, Type type, HttpStatusCode statusCode, ErrorModel errorModel = null)
        {
            if (context.Response == null && context.Exception.GetType() == type)
            {
                context.Response = context.Request.CreateResponse(
                    statusCode,
                    errorModel ?? new ErrorModel { ErrorStatusCode = (int)ErrorCodes.UnknownError, ErrorMessage = context.Exception.Message });
            }

            return context;
        }
    }
}